﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BIG = System.Numerics.BigInteger;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace PodpisyElektorniczne.Classes
{
    public class UserKeyFactory
    {
        public UserKeys KeyPair { get; protected set; }

        public UserKeyFactory()
        {
            KeyPair = new UserKeys();
        }


        /// <summary>
        /// Serialize the KeyPair
        /// </summary>
        /// <param name="path">String a file path.</param>
        /// <returns>True if succed, false otherwise.</returns>
        public bool Serialize(string path)
        {
            try
            {
                var paths = path.Split('\\');

                if (!Directory.Exists(string.Format("{0}\\{1}\\{2}", paths[0],paths[1], paths[2])))
                    Directory.CreateDirectory(string.Format("{0}\\{1}\\{2}", paths[0], paths[1], paths[2]));
                
                using(var writer = new StreamWriter(path,false, Encoding.Unicode))
                {
                    new XmlSerializer(typeof(List<byte[]>)).Serialize(writer, new List<byte[]>{KeyPair.GetPrivateKey().ToByteArray(), KeyPair.Y.ToByteArray()});
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("There is problem with serialization of a key. \n" + ex.Message);
            }
        }

        /// <summary>
        /// Deserialize the KeyPair
        /// </summary>
        /// <param name="path">String a file path.</param>
        /// <returns>UserKeys</returns>
        public bool Deserialize(string path)
        {
            try
            {
                
                using (var reader = new StreamReader(path,Encoding.Unicode))
                {
                    var raw = (List<byte[]>)new XmlSerializer(typeof (List<byte[]>)).Deserialize(reader);
                    this.KeyPair = new UserKeys(raw[0], raw[1]);
                }
                return (KeyPair == null);
            }
            catch (Exception ex)
            {
                throw new Exception("It was not opssible to read your key pair. \n" + ex.Message);
            }
        }

        

    }
}
